package cn.stylefeng.guns.modular.system.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.stylefeng.guns.config.properties.GunsProperties;
import cn.stylefeng.guns.core.common.annotion.BussinessLog;
import cn.stylefeng.guns.core.common.annotion.Permission;
import cn.stylefeng.guns.core.common.constant.Const;
import cn.stylefeng.guns.core.common.constant.dictmap.UserDict;
import cn.stylefeng.guns.core.common.constant.factory.ConstantFactory;
import cn.stylefeng.guns.core.common.constant.state.ManagerStatus;
import cn.stylefeng.guns.core.common.exception.BizExceptionEnum;
import cn.stylefeng.guns.core.common.node.TreeviewNode;
import cn.stylefeng.guns.core.common.node.ZTreeNode;
import cn.stylefeng.guns.core.common.page.LayuiPageFactory;
import cn.stylefeng.guns.core.log.LogObjectHolder;
import cn.stylefeng.guns.core.shiro.ShiroKit;
import cn.stylefeng.guns.core.shiro.ShiroUser;
import cn.stylefeng.guns.modular.system.entity.Brand;
import cn.stylefeng.guns.modular.system.entity.Notice;
import cn.stylefeng.guns.modular.system.entity.SysDrugModel;
import cn.stylefeng.guns.modular.system.entity.User;
import cn.stylefeng.guns.modular.system.factory.UserFactory;
import cn.stylefeng.guns.modular.system.model.UserDto;
import cn.stylefeng.guns.modular.system.service.BrandService;
import cn.stylefeng.guns.modular.system.service.SysDrugServiceImpl;
import cn.stylefeng.guns.modular.system.service.TypesService;
import cn.stylefeng.guns.modular.system.service.UserService;
import cn.stylefeng.guns.modular.system.warpper.UserWrapper;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.datascope.DataScope;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.RequestEmptyException;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zangsh
 * @since 2022-07-28
 */
@Controller
@RequestMapping("/drug")
public class SysDrugController extends BaseController {

    private static String PREFIX = "/modular/system/drug/";

    //志愿者权限ID
    private static final String VOLUNTEER = "7";
    private static final String NO_VOLUNTEER = "6";


    @Autowired
    private GunsProperties gunsProperties;

    @Autowired
    private SysDrugServiceImpl sysDrugService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private UserService userService;

    @Autowired
    private TypesService typesService;

    @RequestMapping("")
    public String index() {
        return PREFIX + "drug.html";
    }

    /**
     * 修改状态开关
     *
     */
//    @RequestMapping("/status")
//    @BussinessLog(value = "商品状态", key = "drug", dict = UserDict.class)
//    @Permission(Const.ADMIN_NAME_KZ)
//    @ResponseBody
//    public ResponseData status(@RequestParam Long id,@RequestParam String status) {
//        SysDrugModel sysDrugModel = new SysDrugModel();
//        sysDrugModel.setId(id);
//        sysDrugModel.setStatus(status);
//        sysDrugService.updateById(sysDrugModel);
//        return SUCCESS_TIP;
//    }

    /**
     * 修改
     *
     */
    @RequestMapping("/edit")
    @BussinessLog(value = "修改", key = "drug", dict = UserDict.class)
    @ResponseBody
    public ResponseData edit(@Valid SysDrugModel drug, BindingResult result) {
        if (result.hasErrors()) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        sysDrugService.updateById(drug);
        return SUCCESS_TIP;
    }

    /**
     * 状态
     *
     */
    @RequestMapping("/status")
    @BussinessLog(value = "状态", key = "drug", dict = UserDict.class)
    @ResponseBody
    public ResponseData status(@Valid SysDrugModel drug, BindingResult result) {
        if (result.hasErrors()) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        sysDrugService.updateById(drug);
        return SUCCESS_TIP;
    }

    /**
     * 获取详情
     *
     */
    @RequestMapping("/getDrugInfo")
    @ResponseBody
    public Object getDrugInfo(@RequestParam Long id) {
        if (ToolUtil.isEmpty(id)) {
            throw new RequestEmptyException();
        }
        SysDrugModel sysDrugModel = this.sysDrugService.getById(id);
        return ResponseData.success(sysDrugModel);
    }

    /**
     * 跳转到编辑页面
     *
     */
//    @Permission
    @RequestMapping("/drug_edit")
    public String drugEdit(@RequestParam Long id) {
        if (ToolUtil.isEmpty(id)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        getVolunteer();
        SysDrugModel sysDrugModel = this.sysDrugService.getById(id);
        LogObjectHolder.me().set(sysDrugModel);
        return PREFIX + "drug_edit.html";
    }

    /**
     * 跳转到编辑页面
     *
     */
//    @Permission
    @RequestMapping("/drug_show")
    public String drugShow(@RequestParam Long id) {
        if (ToolUtil.isEmpty(id)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        getVolunteer();
        SysDrugModel sysDrugModel = this.sysDrugService.getById(id);
        LogObjectHolder.me().set(sysDrugModel);
        return PREFIX + "drug_show.html";
    }

    /**
     * 跳转到状态管理页面
     *
     */
//    @Permission
    @RequestMapping("/drug_status")
    public String drugStatus(@RequestParam Long id) {
        if (ToolUtil.isEmpty(id)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        getVolunteer();
        SysDrugModel sysDrugModel = this.sysDrugService.getById(id);
        LogObjectHolder.me().set(sysDrugModel);
        return PREFIX + "drug_status.html";
    }

    /**
     * 删除（逻辑删除）
     *
     *
     *
     */
    @RequestMapping("/delete")
    @BussinessLog(value = "删除商品", key = "drug", dict = UserDict.class)
    @Permission(Const.ADMIN_NAME_KZ)
    @ResponseBody
    public ResponseData delete(@RequestParam Long id) {
        if (ToolUtil.isEmpty(id)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.set("STATUS",1);
        updateWrapper.eq("ID",id);
        this.sysDrugService.update(updateWrapper);
        return SUCCESS_TIP;
    }

    /**
     * 保存
     *
     *
     *
     */
    @RequestMapping("/add")
    @BussinessLog(value = "保存商品内容", key = "drug", dict = UserDict.class)
//    @Permission(Const.ADMIN_NAME_KZ)
    @ResponseBody
    public ResponseData add(@Valid SysDrugModel param, BindingResult result) {
        if (result.hasErrors()) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        param.setCreateTime(DateUtil.date());
        param.setUpdateTime(DateUtil.date());
        this.sysDrugService.save(param);
        return SUCCESS_TIP;
    }

    /**
     * 添加
     *
     */
    @RequestMapping("/drug_add")
    public String addView() {
        getVolunteer();
        return PREFIX + "drug_add.html";
    }

    private void getVolunteer() {
        //分类
        List<ZTreeNode> tree = typesService.tree();
        //品牌
        List<Brand> brandList = brandService.listNoPage();
        super.setAttr("typesList",tree);
        super.setAttr("brandList", brandList);
    }

    /**
     * 查询列表
     *
     */
    @RequestMapping("/list")
//    @Permission(Const.ADMIN_NAME_KZ)
    @ResponseBody
    public Object list(@RequestParam(required = false) String name,
                       @RequestParam(required = false) String timeLimit) {

        //拼接查询条件
        String beginTime = "";
        String endTime = "";

        if (ToolUtil.isNotEmpty(timeLimit)) {
            String[] split = timeLimit.split(" - ");
            beginTime = split[0];
            endTime = split[1];
        }

//        if (ShiroKit.isAdminAndZyz()) {
//            Page<Map<String, Object>> users = sysDrugService.selectDrug(null, name, beginTime, endTime, null);
//            Page wrapped = new UserWrapper(users).wrap();
//            return LayuiPageFactory.createPageInfo(wrapped);
//        } else {
//            Long userId = null;
//            ShiroUser user = ShiroKit.getUser();
//            List<Long> roleList = user.getRoleList();
//            //居民
//            if (roleList.size()==1 && roleList.get(0)==6){
//                userId = user.getId();
//            }
            Page<Map<String, Object>> users = sysDrugService.selectDrug(null, name, beginTime, endTime, null);
            Page wrapped = new UserWrapper(users).wrap();
            return LayuiPageFactory.createPageInfo(wrapped);
//        }
    }
}
